<?php
/* 
 *产品管理
 */
class ProductAction extends CommonAction {
    public function _filter(&$map) {
        $key = trim($_REQUEST['keywords']);
        if(strpos($key, ' ')){ //高级搜索，仅搜索产品名称
            $map = A('Search')->search($key);
        }else{//普通搜索
            if(!empty($key)) {
                $where['tm'] = array('like',"%".$key."%");
                $where['name'] = array('like',"%".$key."%");
                $where['helpword'] = array('like',"%".$key."%");
                $where['_logic'] = 'or';
                $map['_complex'] = $where;
                $map['common_id'] = array('gt',0);
               // $map['cost_default'] = array('like',"%".$key."%");
                //$map['_logic'] = "or";
            }
        }
        
    }

    //专门过滤搜索，供选择产品
    public function search(){
        $map = $this->_search ();
        $this->_filter ( $map );
        $map['common_id'] = array('gt',0);
        $map['status'] = 1; //正常产品才供搜索
        $model = D ('Product');
        //默认按名称升序排列，便于查找度数
        $this->_list ( $model, $map,'name',true );
        $this->display();
    }

    public function index()
    {
        $parameters = str_replace(__URL__.'?', '', __SELF__);
        $this->assign('parameters' ,$parameters);
        parent::index();
    }

    //专门过滤搜索，供选择产品
    public function search_single(){
       $this->search();
    }

    public function _before_add(){
        //$this->assign('cate_list',D('Category')->getAllCatalog(0,0));
        //$this->assign('units',M('Unit')->where('status=1')->getField('id,name'));
        //$this->assign('suppliers',M('Supplier')->where('status=1')->getField('id,name'));
    }


    //处理option,排列组合 生成货品
    public function create_option(){
         $common_id = $_POST['common_id']; //产品ID
         if(empty($common_id) || !is_numeric($common_id))
            $this->error('请先选择产品！');
         $options = $_POST['option_value'];
         $values = M('Option_value')->where(array('mano'=> array( 'in',$options )))->order('option_id desc')->findAll();
         $group = array();
         foreach($values as $key => $value){
             if($values[$key-1]['option_id'] == $value['option_id']   ){
                  $group[$value['option_id']] .=','. $value['mano'];
             }else{
                 $group[$value['option_id']] = $value['mano'];
             }
         }
         foreach($group as $k=> $va){
             $group[$k] = explode(',',$va);
         }
         if(count($group) > 1 ) //二维以上才使用笛卡尔积
            $r = Descartes($group);  
         else{
            $r = $group;
            $only_one = 1; //仅一维度的,便于分开显示
         }
            

        $val = array(
           'options' => $r,
           'common_id' => $common_id,
           'only_one' => $only_one
        );
        $this->assign($val);
        $this->display();
    }

   //mass insert goods with different options
    public function mass_insert(){
        $product = M('Common_product') ->getById($_POST['common_id']);
        $brand = M('Brand')->getById($product['brand_id']);
        $data = array();
        $len = count($_POST['pnumber']);
        if(empty($_POST['common_id']) || $len == 0 ){
            $this->error('添加货品出错,请返回重新操作!');
        }
        $goods = D('Product');
       for ($i = 0; $i < $len; $i++ ){
          $data = array(
             'common_id' => $_POST['common_id'],
             'name' => $product['name'] . $_POST ['sname'][$i],  // goods name = pname+ option name 
             'pnumber' => $product ['mano'].$brand ['mano'].$_POST ['pnumber'][$i],
             'location' => $_POST['location'][$i],
             'tm' => $_POST['tm'][$i],
             'minstock' => $_POST['minstock'][$i],
             'cat_id' => $product['cat_id'],
             'unit_id' => $product ['unit_id'],

             'brand_id' => $product ['brand_id'],
             'cost_default' => $product ['cost_default'],
             'sale_price_default' => $product ['sale_price_default'],
             'wholesale_price_default' => $product ['wholesale_price_default'],
             'supplier_id_default' => $product ['supplier_id_default'],
             'helpword' => $product ['helpword'],
             'regcode' => $product ['regcode'],
             'warehouse_id' => $product ['warehouse_id'],
             'create_time' => time(),
          ); 
          //dump($data);
          $goods->add ($data);
          unset($data);
       }
       $this->assign('jumpUrl','__URL__/');
       $this->success('批量增加'.$len.'货品成功!',false,10);
    } 

    public function _before_edit(){
        $this->assign('mod_options',M('Option') ->where('status = 1')->findAll() );
        $this->assign('cate_list',D('Category')->getAllCatalog(0,0));
        $this->assign('units',M('Unit')->where('status=1')->getField('id,name'));
        $this->assign('suppliers',M('Supplier')->where('status=1')->getField('id,name'));
    }

    /**
     * 隐形眼镜的产品复制，增加光度及条码
     */
    public function copyProduct() {
        $model = M('Product');
        $id = $_REQUEST ['pid'];
        $copyNumber = intval($_REQUEST ['copynum']);
        $copyData = array();
        $g = 1.00; //光度计数
        $tm = '';   //条码

        if (isset ( $id )) {
            $condition = array ('id' => array ('in', explode ( ',', $id ) ) );
            $list=$model->where ( $condition )->findAll();
            if(!is_array($list))
                $this->error('您选择的产品不存在！');
            foreach($list as $val) {
                unset($val['id']);
                unset($copyData);
                $val['create_time'] = $val['update_time']= time();
                $copyData = $val;

                $tm = intval($val['tm'])+11;
                $copyData['name'] = $val['name'].'-'.sprintf("%1.2f",$g );
                $copyData['tm'] = sprintf("%010d",$tm );
                $model->add($copyData); //先存入最初始0.25度
                    //光度以25度递增,最高计算到1000度。共计29个
                    for($i=1; $i<=28; $i++){
                        if($g == $copyNumber)
                            break;
                        
                        if($g <6.00)
                            $g =$g+0.25;
                        else
                            $g =$g+0.50;
                        $tm = $tm+11;
                        $copyData['name'] = $val['name'].'-'.sprintf("%1.2f",$g );
                        $copyData['tm'] = sprintf("%010d",$tm );
                        unset ($copyData['id']);
                        $model->add($copyData);
                    }
                    
                    //reset
                    $g = 0.25;
                    $tm = '';
            }
                $this->success ('复制成功！' );
            
        } else {
            $this->error ( '非法操作' );
        }
    }

    /**
     * 产品批量修改页
     */
    public function massedit() {
        $id = $_REQUEST ['pid'];

        if (!isset($id)) {
            $this->error('请先选择产品！');
        }
        $model = M('Product');
        $condition = array('id' => array('in', explode(',', $id)));
        $list = $model->where($condition)->field('id,tm,name')->findAll();
        if (!is_array($list))
            $this->error('您选择的产品不存在！');

        $this->assign('list', $list);
        $this->_before_edit();
        $this->display();
    }

    /**
     * 产品批量修改页 helpword
     */
    public function massedit_helpword() {
        $id = $_REQUEST ['pid'];

        if (!isset($id)) {
            $this->error('请先选择产品！');
        }
        $start_mano = trim($_REQUEST ['start_mano']);

        $model = M('Product');
        $condition = array('id' => array('in', explode(',', $id)));
        $list = $model->where($condition)->field('id,pnumber,name')->findAll();
        if (!is_array($list))
            $this->error('您选择的产品不存在！');
        $level = 0;
        foreach ($list as $key => $value) {
            $options = getGoodsDetail($value['id']);
            $option_str = "";
            foreach ($options['option'] as $op) {
                if($op['option'] =="光度"){
                    $level = -floatval($op['name'])*100 ;
                    break;
                }
            }
            if($level >= 0){
                $level = sprintf("%03d", $level );
                $list[$key]['helpword'] = $start_mano.$level;
            }
            else
                continue;
            
        }
        $this->assign('list', $list);
        $this->_before_edit();
        $this->display();
    }

    //temp used to process mano-helpword update
    public function mass_update()
    {
        $data = $_POST;
        $count_no = count($data['helpword']);
       
        for($i =0; $i < $count_no;$i++) {
          if( $data['helpword'][$i] ==''  )
            continue;
          
          $_POST = array(
            'id' => $data['id'][$i],
            'helpword' => trim($data['helpword'][$i]),
            );
          if($rs = M('Product')->where('helpword = "'.$_POST['helpword'].'"')->getField('id') )
            $this->error($_POST['helpword']."编码存在重复，请更换！");
          $this->micro_update();

          unset($_POST);
        }

        $jumpUrl = $_REQUEST['jumpUrl'];
        if(empty($jumpUrl))
            $jumpUrl = Cookie::get ( '_currentUrl_' );
        $this->assign ( 'jumpUrl', $jumpUrl );
        $this->success ('批量修改成功!');
    }

    /**
     * 批量修改处理
     */
    public function massUpdate(){
        if(empty ($_POST['product_id']))
            $this->error ("请选择要修改的产品");
        $data = $_POST;
        $changes = array();

        if(!empty ($data['regcode']))
            $changes['regcode'] = $data['regcode'];
        /*代替做为人工编码
        if(!empty ($data['helpword']))
            $changes['helpword'] = $data['helpword']; 
        */
        if(!empty ($data['cost_default']))
            $changes['cost_default'] = $data['cost_default'];
        if(!empty ($data['sale_price_default']))
            $changes['sale_price_default'] = $data['sale_price_default'];
        if(!empty ($data['wholesale_price_default']))
            $changes['wholesale_price_default'] = $data['wholesale_price_default'];
        if(!empty ($data['minstock']))
            $changes['minstock'] = $data['minstock'];
        if(!empty ($data['remark']))
            $changes['remark'] = $data['remark'];

        if( $data['unit_id'] != -1 )
           $changes['unit_id'] = $data['unit_id'];
        if( $data['cat_id'] != -1 )
           $changes['cat_id'] = $data['cat_id'];
        if( $data['supplier_id_default'] != -1 )
           $changes['supplier_id_default'] = $data['supplier_id_default'];
        if( $data['status'] != -1 )
           $changes['status'] = $data['status'];

        $map = array();
        $map['id'] = array('in',$_POST['product_id']);
        $old = M('Product')->where($map)->find();

        $records = M('Product')->where($map)->save($changes);
        if($records == 0)
            $this->error('批量修改失败！');

        //修改成功,记录日志
        $new = M('Product')->where($map)->find();
        $mod_field = getModelName($_POST['product_id']['0'], 'Product');
        $msg = '批量修改 Product: ' . $mod_field . ' (编号：' . implode(',',$_POST['product_id']) . ')';
        A('Action')->writeLog($msg, '批量修改', 'Product', implode(',',$_POST['product_id']), $old, $new);

        $this->assign ( 'jumpUrl', Cookie::get ( '_currentUrl_' ) );
        $this->success('批量修改成功 '.$records.' 个产品！',false,2);
    }

    public function update(){
         $values = $_POST['mano'];
         $common_id = $_POST['common_id'];
         $product = M('Common_product')->getById($common_id );
         $brand_mano = getModelName($product ['brand_id'] ,'Brand','mano');
         $_POST['brand_id'] = $product ['brand_id'];
         $pmano = implode('',$_POST['mano'] );
         if(!empty($pmano )){
           //如果修改了规格,则重新生成商品编码 
             $pnumber = $product ['mano'].$brand_mano .$pmano ;
             $_POST['pnumber'] = $pnumber;
         }else{
             if($_POST['is_update_mano'] == "on" ){
                 $pnumber = $product ['mano'].$brand_mano ;
                 $_POST['pnumber'] = $pnumber;
            }
         }
         parent::update();
    }

    public function import_insert() {
        header("Content-Type:text/html; charset=utf-8");
        set_time_limit(0);
        
        import('@.ORG.PHPExcel.IOFactory','','.php');
        spl_autoload_register(array('Think','autoload'));   //必须重置，否则造成原TP类无法识别

        //处理上传文件
        if ($_FILES['upload']['name'] == '' || $_FILES['upload']['size'] <= 0)
            $this->error('请上传正确文件!');
        $ext = strtolower(substr($_FILES['upload']['name'], strrpos($_FILES['upload']['name'], '.') + 1));
        if ($ext != 'xls' && $ext != 'xlsx')
            $this->error('本功能仅支持excel');
        $filename = date('YmdHis') . '_product.xls';
        $status = move_uploaded_file($_FILES['upload']['tmp_name'], TEMP_PATH . $filename); //到temp目录
        if (!$status) {
            $this->error('上传失败，请重新上传');
            exit;
        }

        $inputFileName = TEMP_PATH . $filename;
        $objPHPExcel = PHPExcel_IOFactory::load($inputFileName);
        $sheetData = $objPHPExcel->getActiveSheet()->toArray(null, true, true, true);
        unlink(TEMP_PATH  . $filename); //上传后删除文件
        if (!$sheetData) {
            $this->error('上传数据失败或者上传的数据为空');
        }
        $this->__saveProduct($sheetData);
    }

    protected  function __saveProduct($sheetData) {
       $product = M('Product');
        $data = array();
        $max_pid = $product->max('id');
        $i = 0; //产品计数

        //创建一个临时表，在500条数据以上时效率倍增，提高10-100倍以上
        $temp_sql = "create temporary table vm_tmp_product (id int(11) NOT NULL auto_increment PRIMARY KEY,pnumber varchar(20) default NULL,tm varchar(50)
            ,name varchar(100),cate varchar(100),unit varchar(50),supplier varchar(50),minstock int(11),
            cost_default float(10,2),sale_price_default float(10,2),wholesale_price_default float(10,2),
            unit_id int(3),cate_id int(3),supplier_id int(3),helpword varchar(50), create_time int(11)
            ) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;";
        M()->execute($temp_sql);
        $tmp_product = M('Tmp_product');

        foreach ($sheetData as $key => $value) {
            //$value = iconv("utf-8", "gb2312", var_export($value, true));    //转化为中文编码
            if ($key > 1) {//从第二行开始读取
                if(empty($value['B']) || empty ($value['C']) )
                   continue;
               $data = array(
                   'pnumber' => trim($value['A']),
                   'tm' => trim($value['B']),
                   'name' => trim($value['C']),
                   'cate' => trim($value['D']),   //分类名称
                   'unit' => trim($value['E']),   //单位名称，必须与系统中的名称一致
                   'minstock' => $value['F'],
                   'cost_default' => $value['G'],
                   'wholesale_price_default' => $value['I'],
                   'sale_price_default' => $value['H'],
                   'supplier' => trim($value['J']),   //供应商名称，必须与系统中的供应商名称一致
                   'helpword' => trim($value['K']),   //人工编码
                   'create_time' => time()
               );
                    $pid = $tmp_product->add($data);    //存入临时表
                if ($pid == 0) {
                    continue;
                }
            }
        }

        //连接多个表操作，获得临时表对应的几个外表的主键ID
        $update_sql = 'Update vm_tmp_product a ,vm_category c,vm_unit u,vm_supplier s
            set a.cate_id=c.id,a.unit_id = u.id,a.supplier_id=s.id
         where a.cate=c.name and a.unit=u.name and a.supplier= s.name';
        M()->execute($update_sql);
        //将临时表中的新数据插入到正式的产品表 增加ignore，如果表中存在相应记录，则忽略，继续其他数据插入
        $insert_sql = 'insert ignore  vm_product(pnumber,tm,name,cat_id,unit_id,supplier_id_default,minstock,cost_default,wholesale_price_default,sale_price_default,helpword,create_time)
            select pnumber,tm,name,cate_id,unit_id,supplier_id,minstock,cost_default,wholesale_price_default,sale_price_default,helpword,create_time from vm_tmp_product
            ';
        $i = M()->execute($insert_sql);
        //drop tmp table
        M()->execute('Drop table vm_tmp_product');

        if($i == 0)
            $this->error ("可能与系统中的产品重复，上传0个,请重新上传");
        
        $message = '批量上传'.$i . '个产品';
        A('Action')->writeLog($message,'批量新增','Product',$max_pid);
        $this->assign('jumpUrl', '__APP__/Product/index');
        $this->success($message,false,2);
    }

    //导出产品 csv
    public function export()
    {
      $map = $this->_search ();
      $this->_filter ( $map );
      $line = "";
      $data = array();
      $voList = M('Product')->where($map)->group('id')->findAll( );
       $title ="编号,系统编号,人工编码,名称,类别,品牌,单位,零售价,批发价,默认供应商,库位,是否虚拟产品\n";
        $title = iconv('utf-8', 'GBK', $title);
        if( is_array($voList) )
        foreach ($voList as $key => $value) {
          $data= array(
             'id' => $value['id'],
             'pnumber' => $value['pnumber'],
             'helpword' => iconv('utf-8','GBK',$value['helpword'] ),
             'name' => iconv('utf-8','GBK',$value['name'] ),

             'Category' => iconv('utf-8','GBK',getModelName($value['category_id'],'Category') ),
             'brand' => iconv('utf-8','GBK',getModelName($value['brand_id'],'Brand') ),
             'unit' => iconv('utf-8','GBK',getModelName($value['unit_id'],'Unit') ),
             'sale_price' => $value['sale_price_default'],
             'wholesale_price_default' => $value['wholesale_price_default'],
             'Supplier' => iconv('utf-8','GBK',getModelName($value['supplier_id'],'Supplier') ),
             
             'location' => $value['location'],
              'is_virtual' => $value['is_virtual'],
             );
            $line .= build_csv_line($data);
            unset($data);
        } 
        $filename = "DYW_goods".date('Ymd_His').'.csv'; //设置文件名 
        
        export_csv($filename,$title.$line);
        
    }

}
?>
